package com.bupt.kgplatform.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.bupt.kgplatform.component.DynamicDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class DynamicDataSourceConfiguration {
    /**
     * 创建数据源对象
     * @return data source
     */
    private DruidDataSource createDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        System.out.println("+++default默认数据库连接url+++");
        dataSource.setUrl("jdbc:mysql://114.67.200.41:3306/kgplatform?serverTimezone=GMT%2B8&characterEncoding=utf-8&useSSL=false");
        dataSource.setUsername("root");
        dataSource.setPassword("85PU*LvL+VzvGl2X");
//        dataSource.setUrl("jdbc:mysql://localhost:3306/kgplatform");
//        dataSource.setUsername("root");
//        dataSource.setPassword("zhu20001129");
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        return dataSource;
    }

    /**
     * spring boot 启动后将自定义创建好的数据源对象放到TargetDataSources中用于后续的切换数据源用
     *             (比如：DynamicDataSourceContextHolder.setDataSourceKey("dbMall")，手动切换到dbMall数据源
     * 同时指定默认数据源连接
     * @return 动态数据源对象
     */
    @Bean
    public DynamicDataSource dynamicDataSource() {
        //获取动态数据库的实例（单例方式）
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        //创建默认数据库连接对象
        DruidDataSource defaultDataSource = createDataSource();


        Map<Object,Object> map = new HashMap<>();
        //自定义数据源key值，将创建好的数据源对象，赋值到targetDataSources中,用于切换数据源时指定对应key即可切换
        map.put("default", defaultDataSource);
        dynamicDataSource.setTargetDataSources(map);
        //设置默认数据源
        dynamicDataSource.setDefaultTargetDataSource(defaultDataSource);

        return dynamicDataSource;
    }
}
